package com.znyj.cloud.device.util;

import java.util.Random;

/**
 * Created by hexin.duan on 15-1-15.
 */
public class RandomUtil {

    private static char str[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8',
            '9', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L',
            'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y',
            'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l',
            'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y',
            'z', '0', '1'};

    private static char number[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8',
            '9', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '1',
            '9', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '1',
            '9', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '1',
            '9', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '1',
            '2', '3', '4'};

    private static Random random = new Random();

    public static String getRandomString(int length) {
        String strRandom = "";
        if (length > 0) {
            int index = 0;
            char[] temp = new char[length];
            int num = random.nextInt();
            for (int i = 0; i < length % 5; i++) {
                temp[index++] = str[num & 63];
                num >>= 6;
            }
            for (int i = 0; i < length / 5; i++) {
                num = random.nextInt();
                for (int j = 0; j < 5; j++) {
                    temp[index++] = str[num & 63];
                    num >>= 6;
                }
            }
            strRandom = new String(temp, 0, length);
        }
        return strRandom;
    }

    /**
     * 生成纯数字的随机数
     *
     * @param length
     * @return
     */
    public static String getRandomNumber(int length) {
        String strRandom = "";
        if (length > 0) {
            int index = 0;
            char[] temp = new char[length];
            int num = random.nextInt();
            for (int i = 0; i < length % 5; i++) {
                temp[index++] = number[num & 63];
                num >>= 6;
            }
            for (int i = 0; i < length / 5; i++) {
                num = random.nextInt();
                for (int j = 0; j < 5; j++) {
                    temp[index++] = number[num & 63];
                    num >>= 6;
                }
            }
            strRandom = new String(temp, 0, length);
        }
        return strRandom;
    }

    public static void main(String arg[]) {
        System.out.println(getRandomString(100));
        System.out.println(getRandomNumber(100));
    }
}
